// 请求模块
import axios from 'axios';
import { BASE_URL } from '../constants/api';
import { useNavigate } from 'react-router-dom';

const req = axios.create({
    timeout: 10000,
    baseURL: BASE_URL,
});

// 请求拦截
req.interceptors.request.use((config) => {
    config.headers = {
        ...config.headers,
        Authorization: localStorage.getItem('Vue2_HR_ACCESS_TOKEN'),
    };
    return config;
});

// 响应拦截

function gotoLogin() {
    const goto = useNavigate();
    return goto('/login');
}
req.interceptors.response.use(
    // 成功回调
    (res) => res,
    // 失败回调
    (err) => {
        switch (err.response.status) {
            case 401:
                gotoLogin();
                break;

            default:
                break;
        }
        return Promise.reject(err);
    },
);

export default req;
